<template>
  <div class="image-selector-comp">
    <el-dialog title="图片库" width="70%" :visible.sync="dialogVisible" :before-close="closeDialog">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="文件原名" prop="originalName">
          <el-input
            v-model="queryParams.originalName"
            placeholder="请输入文件原名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="图片类型" prop="shelf">
          <el-select v-model="queryParams.imgType" placeholder="图片类型" clearable>
            <el-option
              v-for="dict in dict.type.app_image_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImage">上传图片</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="ossList" height="65vh" width="100vh">
        <el-table-column label="选择" width="55" align="center">
          <template slot-scope="scope">
            <el-radio
              style="margin-left: 10px"
              v-model="selectedItem"
              :label="scope.row"
              @change="handleRadioChange"
            >
              <span v-show="false">-</span>
            </el-radio>
          </template>
        </el-table-column>

        <el-table-column label="对象存储主键" align="center" prop="ossId" v-if="false"/>
        <el-table-column label="文件原名" align="center" prop="originalName"/>
        <el-table-column label="文件展示" align="center" prop="url">
          <template slot-scope="scope">
            <el-image
              v-if="checkFileSuffix(scope.row.fileSuffix)"
              style="width: 100px; height: 100px"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
            />
            <span v-text="scope.row.url" v-if="!checkFileSuffix(scope.row.fileSuffix)"/>
          </template>
        </el-table-column>
        <el-table-column label="文件类型" align="center" prop="imgType" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.app_image_type" :value="scope.row.imgType"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        :autoScroll = "false"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirmSelect">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-select v-model="upload.data.imgType" placeholder="图片类型" clearable>
        <el-option
          v-for="dict in dict.type.app_image_type"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      <br>
      <br>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jpg, .png, .gif, .jpeg"
        :auto-upload="false"
        drag
        :headers="upload.headers"
        :action="upload.url"
        :data="upload.data"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :before-upload="beforeFileUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入 jpg、png、jpeg、gif 格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listOss } from "@/api/system/oss";
import { getToken } from "@/utils/auth";

export default {
  name: "image-selector-comp",
  dicts: ["app_image_type"],
  components: {},
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  computed: {},
  watch: {
    dialogVisible(val) {
      // 每次开启弹窗，重新加载图片列表
      if (val) {
        this.queryParams.imgType = "";
        this.queryParams.originalName = undefined;
        this.getList();
      }
    }
  },
  data() {
    return {
      loading: true,
      // OSS对象存储表格数据
      ossList: [],
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: undefined,
        imgType: "",
        originalName:undefined
      },
      selectedItem: "", // 单选，选中的id
      // 用户导入参数
      upload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/resource/oss/upload", // 上传的图片服务器地址
        headers: { Authorization: "Bearer " + getToken() }, // 设置上传的请求头部
        data: {
          imgType: ""
        } // 上传的额外数据，用于文件名
      }
    };
  },
  created() {},
  mounted() {},
  methods: {
    /**
     * 弹窗控制
     */
    closeDialog() {
      this.selectedItem = "";
      this.$emit("update:dialogVisible", false);
    },
    checkFileSuffix(fileSuffix) {
      let arr = ["png", "jpg", "jpeg", "gif", "PNG", "JPG", "JPEG", "GIF"];
      return arr.some(type => {
        return fileSuffix.toLowerCase().indexOf(type) > -1;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.imgType = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 查询OSS对象存储列表
    getList() {
      this.selectedItem = "";
      this.loading = true;
      this.queryParams.params = {};
      let _that = this;
      listOss(this.queryParams).then(response => {
        this.ossList = response.rows;
        this.total = response.total;

        setTimeout(()=>{
          _that.loading = false;
        },600)
      });
    },
    /**
     * 单选框选中
     */
    handleRadioChange(selection) {
      this.selectedItem = selection;
    },
    /**
     * 确认选择
     */
    confirmSelect() {
      this.$emit("confirm", this.selectedItem);
      this.selectedItem = "";
      this.closeDialog();
    },
    /** 图片按钮操作 */
    handleImage() {
      this.upload.open = true;
      this.upload.title = "上传文件";
    },
    beforeFileUpload(file) {
      if (file == undefined) {
        this.$modal.msgError("文件不能为空！");
        return false;
      }
      //校验文件大小
      if (file.size >= 5242880) {
        this.$modal.msgError("文件大小超出5M，请重新上传！");
        return false;
      }
      //校验文件格式
      if (
        file.type != "image/png" &&
        file.type != "image/jpg" &&
        file.type != "image/jpeg" &&
        file.type != "image/gif"
      ) {
        this.$modal.msgError("提示：仅允许导入 jpg、png、jpeg、gif 格式文件！");
        return false;
      }
    },

    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {},
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },
    // 取消按钮
    cancel() {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.data.imgType = "";
      this.$refs.upload.clearFiles();
    },
    /** 发起文件上传 */
    submitFileForm() {
      if (this.upload.data.imgType == "") {
        this.$modal.msgError("文件类型不能为空!");
        return false;
      }
      this.$refs.upload.submit();
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      // 清理
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.data.imgType = "";
      this.$refs.upload.clearFiles();
      // 提示成功，并刷新
      this.$modal.msgSuccess("上传成功");
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.image-selector-comp {
}
</style>
